package cn.amaake.magicplugin.satoken.filter;

import cn.amaake.magicplugin.satoken.config.MagicApiSaTokenConfig;
import cn.amaake.magicplugin.satoken.config.SaTokenMode;
import cn.dev33.satoken.config.SaTokenConfig;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.ssssssss.magicapi.core.config.Constants;

import java.io.IOException;

public class TokenResponseHeaderFilter extends OncePerRequestFilter {

    private final SaTokenConfig saTokenConfig;

    private final MagicApiSaTokenConfig magicApiSaTokenConfig;

    public TokenResponseHeaderFilter(MagicApiSaTokenConfig magicApiSaTokenConfig, SaTokenConfig saTokenConfig){
        this.magicApiSaTokenConfig = magicApiSaTokenConfig;
        this.saTokenConfig = saTokenConfig;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(httpServletRequest){
            @Override
            public String getHeader(String name){
                String token = "";
                if(magicApiSaTokenConfig.getSatokenmode() == SaTokenMode.LOCAL){
                    token = httpServletRequest.getHeader(saTokenConfig.getTokenName());
                    if (!StringUtils.isNotBlank(token)){
                        token = httpServletRequest.getParameter(saTokenConfig.getTokenName());
                    }
                }else{
                    token = httpServletRequest.getHeader("access_token");
                    if (!StringUtils.isNotBlank(token)){
                        token = httpServletRequest.getParameter("access_token");
                    }
                }
                // 先从原本的Request中获取头，如果为空且名字为token，则从参数中查找并返回
                String superHeader = super.getHeader(name);
                if(StringUtils.isNotBlank(token) && name.equals(Constants.MAGIC_TOKEN_HEADER)){
                    return token ;
                }
                return superHeader;
            }
        };
        filterChain.doFilter(requestWrapper, httpServletResponse);
    }


}